#!/bin/bash

version=13.0.9

#if ~/tor-browser_en-US folder exists, prepare to import its user-data (OLDEST folder location)
if [ -d ~/tor-browser_en-US/Browser/TorBrowser/Data/Browser ];then
  mv -f ~/tor-browser_en-US ~/.local/share/tor-browser.temp
#if ~/tor-browser folder exists, prepare to import its user-data (OLD folder location)
elif [ -d ~/tor-browser/Browser/TorBrowser/Data/Browser ];then
  mv -f ~/tor-browser ~/.local/share/tor-browser.temp
#if ~/.local/share/tor-browser folder exists, prepare to import its user-data (NEW folder location)
elif [ -d ~/.local/share/tor-browser/Browser/TorBrowser/Data/Browser ];then
  mv -f ~/.local/share/tor-browser ~/.local/share/tor-browser.temp
fi

rm -f /tmp/tor.tar.xz
wget -O /tmp/tor.tar.xz https://sourceforge.net/projects/tor-browser-ports/files/${version}/tor-browser-linux-armhf-${version}.tar.xz/download || error "Failed to download!"
status -n "Extracting... "
tar -xf /tmp/tor.tar.xz -C ~/.local/share || error "Failed to extract!"
rm -f /tmp/tor.tar.xz
status_green Done

#if tor-browser.temp folder exists, import its user-data
if [ -d ~/.local/share/tor-browser.temp ];then
  rm -rf ~/.local/share/tor-browser/Browser/TorBrowser/Data/Browser
  mv -f ~/.local/share/tor-browser.temp/Browser/TorBrowser/Data/Browser ~/.local/share/tor-browser/Browser/TorBrowser/Data && rm -rf ~/.local/share/tor-browser.temp
fi

#disable buggy update notification
if [ ! -f ~/.local/share/tor-browser/Browser/distribution/policies.json ];then
  mkdir -p ~/.local/share/tor-browser/Browser/distribution
  echo '{ 
    "policies": {
        "DisableAppUpdate": true
    } 
}' > ~/.local/share/tor-browser/Browser/distribution/policies.json
fi

#copy icon for wayfire
mkdir -p ~/.local/share/icons
cp -f ~/.local/share/tor-browser/Browser/browser/chrome/icons/default/default128.png ~/.local/share/icons/tor-browser.png

echo "[Desktop Entry]
Type=Application
Name=Tor Browser
GenericName=Web Browser
Comment=Tor Browser is +1 for privacy and −1 for mass surveillance
Categories=Network;WebBrowser;Security;
Exec=$HOME/.local/share/tor-browser/Browser/start-tor-browser --class 'tor-browser' --name 'tor-browser'
X-TorBrowser-ExecShell=./Browser/start-tor-browser --detach
Icon=tor-browser
StartupWMClass=tor-browser" > ~/.local/share/applications/tor.desktop
